package com.wz.boot.function.defaultchat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wz.boot.annotation.Function;
import com.wz.boot.annotation.Handle;
import com.wz.boot.constant.Constant;
import com.wz.boot.utils.HttpUtils;
import love.forte.common.ioc.annotation.Beans;
import love.forte.simbot.api.message.events.PrivateMsg;
import love.forte.simbot.api.sender.Sender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Function(
        priority = 0,//这个值不能改，代表是默认的，改了就不行了
        name = "闲聊",
        describe = "闲聊，随机聊，想咋聊咋聊",
        touch = "闲聊模式",
        claName = "RandomChat"
)
@Component
public class DefaultChat {
    final Logger logger = LoggerFactory.getLogger(DefaultChat.class);
    final String requestUrl = "http://api.tianapi.com/txapi/robot/index";
    final String requestKey = "0daf4bf4ee9d40aca3ede135e8f51ffc";

    @Autowired
    private Constant constant;

    @Handle
    public void aiChat(PrivateMsg privateMsg, Sender sender) {
        Map<String, String> params = new HashMap<>(4);
        params.put("key", requestKey);
        params.put("question", privateMsg.getMsgContent().getMsg());
        params.put("uniqueid", privateMsg.getAccountInfo().getAccountCode());
        boolean requestFalseTag = false;
        String web = HttpUtils.get(requestUrl, params, null).getResponse();
        int i = 0;
        JSONObject jsonObject = JSONObject.parseObject(web);
        int code = jsonObject.getInteger("code");
        String reply = "";
        switch (code) {
            case 200: {
                JSONArray newslist = jsonObject.getJSONArray("newslist");
                if (!newslist.isEmpty()) {
                     reply = newslist.getJSONObject(0).getString("reply");
                    sender.sendPrivateMsg(privateMsg, reply);
                }
                break;
            }
            default:{
                if(i++ < 20)
                    aiChat(privateMsg, sender);
                else
                    sender.sendPrivateMsg(privateMsg, "出错啦！");
                    sender.sendPrivateMsg(constant.getAdminQQ(), "天行api接口出错,"+requestUrl);
            }
        }
        logger.info("QQ:{}发来了:{}    机器人回复了:{}",privateMsg.getAccountInfo().getAccountCode(), reply);
    }
}
